﻿using System;
using System.Globalization;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace SwissTransTracker
{
    /// <summary>
    ///     General class for the API, contains methods to retrieve data from transport.opendata.ch
    /// </summary>
    public static partial class Api
    {
        /// <summary>
        ///     Formats a date to send it to the server in the correct format
        /// </summary>
        /// <param name="date">the date to format</param>
        /// <returns>the date as a formated string</returns>
        private static string FormatDate(DateTime date)
        {
            return string.Format("{0}-{1}-{2}", date.Year,
                                 date.Month.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0'),
                                 date.Day.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0'));
        }

        /// <summary>
        ///     Formats time to send it to the server
        /// </summary>
        /// <param name="date">the time to format</param>
        /// <returns>the time as a formated string</returns>
        private static string FormatTime(DateTime date)
        {
            return string.Format("{0}:{1}", date.Hour.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0'),
                                 date.Minute.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0'));
        }

        /// <summary>
        ///     Formats a boolean to send it to the server
        /// </summary>
        /// <param name="b">the boolean to format</param>
        /// <returns>The boolean as a formated string</returns>
        private static string FormatBool(bool b)
        {
            return b ? "1" : "0";
        }

        /// <summary>
        ///     Function that does the call to the specified URL and deserializes the object
        /// </summary>
        /// <typeparam name="TE">The Type to deserialize</typeparam>
        /// <param name="query">The url/query to go for</param>
        /// <returns>The desired object</returns>
        private static async Task<TE> Fetch<TE>(string query)
        {
            var client = new HttpClient();
            var res = await client.GetAsync(new Uri(query));
            string json = await res.Content.ReadAsStringAsync();
            var r = new Regex("([0-9]{2})d([0-9]{2}):([0-9]{2}):([0-9]{2})");
            json = r.Replace(json, "$1.$2:$3:$4");
            return JsonConvert.DeserializeObject<TE>(json);
        }
    }
}